package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.*;
import com.qf.pojo.*;
import com.qf.service.DtsGoodsService;
import com.qf.service.DtsRoleService;
import com.qf.vo.CatVo;
import com.qf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author lixu
 */
@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {
    @Autowired
    private DtsGoodsMapper dtsGoodsMapper;
    @Autowired
    private DtsRoleService dtsRoleService;
    @Autowired
    private DtsCategoryMapper dtsCategoryMapper;
    @Autowired
    private DtsGoodsProductMapper dtsGoodsProductMapper;
    @Autowired
    private DtsGoodsSpecificationMapper dtsGoodsSpecificationMapper;
    @Autowired
    private DtsGoodsAttributeMapper dtsGoodsAttributeMapper;
    @Autowired
    private DtsBrandMapper dtsBrandMapper;


    public static final String PPGLY = "品牌管理员";
    public static final String CJGLY = "超级管理员";

    @Override
    public Long findCount() {
        return dtsGoodsMapper.selectCount(null);
    }

    /**
     * 商品分页查询
     *
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @param dtsAdmin
     * @return
     */
    @Override
    public IPage<DtsGoods> list(Integer page, Integer limit, String sort, String order, DtsAdmin dtsAdmin) {
        //1. 判断当前登录用户是否为品牌管理员    专卖店(自己的经营的品牌的手机）   华为京东官方 只能自己华为手机
        Integer[] roleIds = dtsAdmin.getRoleIds();
        Set<String> rolesByIds = dtsRoleService.findRolesByIds(roleIds);
        if (CollectionUtils.isEmpty(rolesByIds)) {
            return null;
        } else {
            if (rolesByIds.contains(CJGLY)) {
                //查询所有
                return dtsGoodsMapper.selectPage(new Page<DtsGoods>(page, limit),
                        new QueryWrapper<DtsGoods>()
                                //.like()
                                .orderBy(!StringUtils.isEmpty(sort), "ASC".equalsIgnoreCase(order), sort));
            }
            if (rolesByIds.contains(PPGLY)) {
                //2. 如果是品牌管理员获取管理的品牌数据集合
                Integer id = dtsAdmin.getId();
                Long total = dtsGoodsMapper.findGoodsListCount(id);
                //开始行
                Integer startRow = (page - 1) * limit;
                //每页数
                List<DtsGoods> dtsGoodsList = dtsGoodsMapper.findGoodPageByAdminId(id, startRow, limit);
                Page<DtsGoods> p = new Page<>();
                p.setTotal(total);
                p.setRecords(dtsGoodsList);
                return p;
            }
            //其它管理员不准予查询
            return null;
        }
    }

    @Override
    public DtsGoods findGoodsById(Integer id) {
        return dtsGoodsMapper.selectById(id);
    }


    //查询商品详情信息
    @Override
    public Map<String, Object> findDetailByGoodId(Integer id) {
        //1:商品表
        DtsGoods dtsGoods = dtsGoodsMapper.selectById(id);
        //2:商品分类
        Integer categoryId = dtsGoods.getCategoryId();
        DtsCategory dtsCategory = dtsCategoryMapper.selectById(categoryId);
        Integer[] categoryIds = new Integer[2];
        categoryIds[0] = dtsCategory.getPid();
        categoryIds[1] = dtsCategory.getId();
        //3:商品属性
        List<DtsGoodsAttribute> dtsGoodsAttributeList = dtsGoodsAttributeMapper.
                selectList(new QueryWrapper<DtsGoodsAttribute>()
                        .eq("goods_id", id));
        //4:商品规格
        List<DtsGoodsSpecification> dtsGoodsSpecificationList = dtsGoodsSpecificationMapper.
                selectList(new QueryWrapper<DtsGoodsSpecification>()
                        .eq("goods_id", id));
        //5:库存表
        List<DtsGoodsProduct> dtsGoodsProductList = dtsGoodsProductMapper.
                selectList(new QueryWrapper<DtsGoodsProduct>()
                        .eq("goods_id", id));
        Map<String, Object> data = new HashMap<>();
        data.put("categoryIds", categoryIds);
        data.put("goods", dtsGoods);
        data.put("products", dtsGoodsProductList);
        data.put("attributes", dtsGoodsAttributeList);
        data.put("specifications", dtsGoodsSpecificationList);

        return data;
    }

    @Override
    public Map<String, Object> catAndBrand() {

        //1：商品分类
        List<CatVo> categoryList = dtsCategoryMapper.catAndBrand();

        //2：品牌集合
        List<CatVo> brandList = dtsBrandMapper.catAndBrand();

        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", categoryList);
        data.put("brandList", brandList);
        return data;
    }

    /**
     * 更新商品
     *
     * @param goodsAllinone
     */
    @Override
    @Transactional
    public void update(GoodsAllinone goodsAllinone) {
        //1:商品表
        DtsGoods goods = goodsAllinone.getGoods();
        goods.setUpdateTime(new Date());
        dtsGoodsMapper.updateById(goods);
        //2:库存表
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        //2.1:先将来的库存数据全部删除掉
        dtsGoodsProductMapper.delete(new QueryWrapper<DtsGoodsProduct>()
                .eq("goods_id", goods.getId()));
        //2.2:库存表的添加  批量  要求同学们去SQl  foreach
        for (DtsGoodsProduct product : products) {//100 SQL
            product.setGoodsId(goods.getId());
            dtsGoodsProductMapper.insert(product);//性能太差
        }
        //3:规则表
        dtsGoodsSpecificationMapper.delete(new QueryWrapper<DtsGoodsSpecification>()
                .eq("goods_id", goods.getId()));
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        for (DtsGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            dtsGoodsSpecificationMapper.insert(specification);
        }


        //4:属性表
        dtsGoodsAttributeMapper.delete(new QueryWrapper<DtsGoodsAttribute>()
                .eq("goods_id", goods.getId()));
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        for (DtsGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            dtsGoodsAttributeMapper.insert(attribute);
        }

    }
}
